package cn.com.shadowless.xinning.view.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.slidingpanelayout.widget.SlidingPaneLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mengpeng.mphelper.ToastUtils;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import cn.com.shadowless.xinning.MyApplication;
import cn.com.shadowless.xinning.R;
import cn.com.shadowless.xinning.adapter.BillFragmentLeftAdapter;
import cn.com.shadowless.xinning.adapter.BillFragmentRightAdapter;
import cn.com.shadowless.xinning.callback.RequestCallBack;
import cn.com.shadowless.xinning.model.RequestResult;
import cn.com.shadowless.xinning.model.bill.BillCountInfo;
import cn.com.shadowless.xinning.presenter.BillPresenter;
import cn.com.shadowless.xinning.utils.PreferencesUtils;
import cn.com.shadowless.xinning.utils.WindowUtils;
import cn.com.shadowless.xinning.view.BaseFragment;
import cn.com.shadowless.xinning.view.activity.OrderMoreInfoActivity;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * The type Bill fragment.
 *
 * @author sHadowLess
 */
public class BillFragment extends BaseFragment implements View.OnClickListener, SlidingPaneLayout.PanelSlideListener {

    private final String TAG = BillFragment.class.getSimpleName();

    /**
     * The M activity.
     */
    protected Activity mActivity = null;
    /**
     * The Order left.
     */
    @BindView(R.id.order_left)
    RecyclerView orderLeft;
    /**
     * The Order right.
     */
    @BindView(R.id.order_right)
    RecyclerView orderRight;
    /**
     * The Switch panel.
     */
    @BindView(R.id.switch_panel)
    SlidingPaneLayout switchPanel;

    private ImageView orderTitleListBtn;
    private int i;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_bill_layout;
    }

    @Override
    protected void initData() {
        timer();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mActivity = (Activity) context;
    }

    @Override
    public void onStart() {
        super.onStart();
        timer();
    }

    @Override
    public void onStop() {
        dispose();
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        dispose();
        super.onDestroyView();
    }

    @Override
    protected void initView() {
        SlidingPaneLayout.LayoutParams layoutParamsRight = (SlidingPaneLayout.LayoutParams) orderLeft.getLayoutParams();
        layoutParamsRight.width = WindowUtils.getWidth(mActivity) / 2;
        orderLeft.setLayoutParams(layoutParamsRight);
        orderTitleListBtn = mActivity.findViewById(R.id.order_title_list_btn);
        ImageView orderTitleLogoutBtn = mActivity.findViewById(R.id.order_title_list_exit);
        switchPanel.openPane();
        switchPanel.setPanelSlideListener(this);
        orderTitleListBtn.setOnClickListener(this);
        orderTitleLogoutBtn.setOnClickListener(this);
    }

    private void dispose() {
        if (compositeDisposable.size() != 0 && !compositeDisposable.isDisposed()) {
            compositeDisposable.clear();
        }
    }

    private void timer() {
        Disposable mDisposable = Observable.interval(0, 30, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> initBillInfo());
        compositeDisposable.add(mDisposable);
    }

    private void initBillInfo() {
        String userName = PreferencesUtils.getString(MyApplication.getInstance(), "userName", "-1");
        BillPresenter
                .getSingleton()
                .getBillInfo(userName, new RequestCallBack<BillCountInfo>() {
                    @Override
                    public void success(RequestResult<BillCountInfo> result) {
                        String token = result.getLoginToken();
                        String oldToken = PreferencesUtils.getString(MyApplication.getInstance(), "token", "-1");
                        if (result.isSucceed() && null != result.getResult()) {
                            if (null != token && token.equals(oldToken)) {
                                Log.e(TAG, "success: " + result.toString());
                                orderLeft.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
                                BillFragmentLeftAdapter billFragmentLeftAdapter = new BillFragmentLeftAdapter(
                                        R.layout.adapter_fragment_bill_left_item,
                                        result.getResult().getData()
                                );
                                orderLeft.setAdapter(billFragmentLeftAdapter);
                                billFragmentLeftAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                                    i = position;
                                    switchPanel.closePane();
                                    BillFragmentRightAdapter billFragmentRightAdapter = new BillFragmentRightAdapter(
                                            R.layout.adapter_fragment_bill_right_item,
                                            result.getResult().getData().get(position).getItemList()
                                    );

                                    orderRight.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
                                    orderRight.setAdapter(billFragmentRightAdapter);
                                    billFragmentRightAdapter.setOnItemChildClickListener((adapter1, view1, position1) -> {
                                        String orderId = result.getResult().getData().get(i).getItemList().get(position1).getOrderId();
                                        String billName = result.getResult().getData().get(i).getItemList().get(position1).getBillName();
                                        String billCode = result.getResult().getData().get(i).getItemList().get(position1).getBillCode();
                                        Intent intent = new Intent(mActivity, OrderMoreInfoActivity.class);
                                        intent.putExtra("orderId", orderId);
                                        intent.putExtra("billCode", billCode);
                                        intent.putExtra("billName", billName);
                                        intent.putExtra("userName", userName);
                                        mActivity.startActivity(intent);
                                        mActivity.finish();
                                    });
                                    billFragmentRightAdapter.notifyDataSetChanged();
                                });
                                billFragmentLeftAdapter.notifyDataSetChanged();

                            } else {
                                ToastUtils.onErrorShowToast("登录态与服务器不一致");
                                initLogoutInfo(mActivity, userName);
                            }
                        } else {
                            ToastUtils.onErrorShowToast("暂无订单列表");
                        }
                    }

                    @Override
                    public void fail(String errorMsg) {
                        ToastUtils.onErrorShowToast(errorMsg);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.order_title_list_btn:
                switchPanel.openPane();
                break;
            case R.id.order_title_list_exit:
                initLogoutInfo1(mActivity, null);
                break;
            default:
                break;
        }
    }

    @Override
    public void onPanelSlide(@NonNull View panel, float slideOffset) {

    }

    @Override
    public void onPanelOpened(@NonNull View panel) {
        orderTitleListBtn.setVisibility(View.GONE);
    }

    @Override
    public void onPanelClosed(@NonNull View panel) {
        orderTitleListBtn.setVisibility(View.VISIBLE);
    }
}
